﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ImageListConverter.cs" company="Roman '4ux-nbIx' Novitsky">
//   Copyright (c) 2012 Roman '4ux-nbIx' Novitsky
// </copyright>
// <summary>
//   Defines the ImageListConverter type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace MonoDevAssist
{
  #region Namespace Imports

  using System;
  using System.Diagnostics.CodeAnalysis;
  using System.Drawing;
  using System.Runtime.InteropServices;
  using System.Windows.Forms;

  #endregion


  internal static class ImageListConverter
  {
    #region Public Methods

    [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "As designed.")]
    public static ImageList FromHandle(IntPtr listHandle)
    {
      var imgList = new ImageList();
      int listCount = NativeMethods.ImageList_GetImageCount(listHandle);
      for (int i = 0; i < listCount; ++i)
      {
        IntPtr iconHandle = NativeMethods.ImageList_GetIcon(listHandle, i, 0);
        if (iconHandle != IntPtr.Zero)
        {
          Icon icon = Icon.FromHandle(iconHandle);
          imgList.Images.Add(icon);
          NativeMethods.DestroyIcon(iconHandle);
        }
      }

      return imgList;
    }

    #endregion


    private static class NativeMethods
    {
      [DllImport("user32.dll")]
      public static extern bool DestroyIcon(IntPtr iconHandle);


      [DllImport("comctl32.dll", CharSet = CharSet.Unicode)]
      public static extern IntPtr ImageList_GetIcon(IntPtr imageListHandle, int index, uint flags);


      [DllImport("comctl32.dll", CharSet = CharSet.Unicode)]
      public static extern int ImageList_GetImageCount(IntPtr imageListHandle);
    }
  }
}